package zy.util;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Random;

import org.apache.commons.lang.math.RandomUtils;

public class IDUtil {
	public static Long buildId(){
		return System.currentTimeMillis() * 1000 + RandomUtils.nextInt(999);
	}
	/**
	 * 产生多个时间戳id
	 */
	public static Long[] buildIds(int n){
		if (n <= 0) {
			return null;
		}
		Long[] ids = new Long[n];
		long id = System.currentTimeMillis() * 1000 + RandomUtils.nextInt(999);
		for (int i = 0; i < n; i++) {
			ids[i] = id+i;
		}
		return ids;
	}
	
	public static String buildNumber() {
		Long time = Long.parseLong(new SimpleDateFormat("yyMMddHHmmssSSS").format(Calendar.getInstance().getTime()))+RandomUtils.nextInt(100);
		return String.valueOf(time);
	}
	
	public static String[] buildNumber(int n) {
		if (n <= 0) {
			return null;
		}
		String[] numbers = new String[n];
		Long time = Long.parseLong(new SimpleDateFormat("yyMMddHHmmssSSS").format(Calendar.getInstance().getTime()))+RandomUtils.nextInt(100);
		for (int i = 0; i < n; i++) {
			numbers[i] = String.valueOf(time+i);
		}
		return numbers;
	}
	/**
	 * 随机生成商家编号--6位数字
	 * YanXue 2012-11-27
	 * @return	商家代码
	 */
	public static String buildCode(int numbers){
		int[] array = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
		Random rand = new Random();
		for (int i = 10; i > 1; i--) {
			int index = rand.nextInt(i);
			int tmp = array[index];
			array[index] = array[i - 1];
			array[i - 1] = tmp;
		}
		int result = 0;
		for (int i = 0; i < numbers; i++){
			result = result * 10 + array[i];
		}
		String str = result + "";
		if(str.length() < numbers){//如果生成的随机数不足以位，加6补齐
			for(int i =0,len=str.length();i<numbers-len;i++){
				str += "5";
			} 
		}
		//如果出现4号码，则重新计算 ,递归
		if(str.indexOf("4") > -1){
			return buildCode(numbers);
		}
		return str;
	}
}
